/**
 * 使用 rollup 的 API 进行自定义打包
 * @author liaoJie
 * @since 2022-06-19 10:57:25
 */
import * as rollup from 'rollup';
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import { terser } from 'rollup-plugin-terser';

/**
 * 输入配置
 * @type { import('rollup').RollupOptions }
 */
const inputOptions = {
  input: './src/index.js',
  plugins: [resolve(), commonjs()],
};

/**
 * 输出配置
 * @type { import('rollup').RollupOptions['output'] }
 */
const outputOptions = [
  {
    format: 'esm',
    dir: 'dist/es',
    entryFileNames: '[name].js',
    chunkFileNames: 'chunk-[name].js',
    sourcemap: true,
    assetFileNames: 'assets/[name]-[hash][extname]',
    // 压缩代码
    // plugins: [terser()],
  },
  {
    format: 'commonjs',
    dir: 'dist/cjs',
  },
];

// 进行打包
async function build() {
  let bundle;
  let buildFailed = false;

  try {
    // 生成 bundle 对象
    bundle = await rollup.rollup(inputOptions);
    console.log(bundle.cache.modules);

    for (const outputOption of outputOptions) {
      // 生成打包产物
      const { output } = await bundle.generate(outputOption);

      // 生成打包产物，并写入磁盘
      await bundle.write(outputOption);
    }
  } catch (error) {
    buildFailed = true;
    console.log('报错', error);
  }

  if (bundle) {
    // 打包成功，结束打包
    bundle.close();
  }

  process.exit(buildFailed ? 1 : 0);
}

build();
